import {createRouter, createWebHistory} from "vue-router";
import {takeAccessToken} from "@/utils/request.js";

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: '/',
            name: 'welcome',
            component: () => import('@/views/WelcomeView.vue'),
            children: [
                {
                    path: '',
                    name: 'welcome-login',
                    component: () => import('@/views/Login/LoginView.vue')
                }
            ]
        },
        {
            path: '/home',
            name: 'loginHome',
            component: () => import('@/views/Login/HomeView.vue')
        }
    ]
})

router.beforeEach((to, from, next) => {
    console.log("to:", to);
    console.log("from:", from);
    // 判断是否登录，登录了才可以进入/home页面
    const isLogin = takeAccessToken();
    console.log("是否登录: ", isLogin)
    if (isLogin != null && to.path !== '/home') {
        console.log("已登录，重定向到 /home");
        next('/home');
    } else if (isLogin == null && to.path === '/home') {
        console.log("未登录，重定向到登录页面");
        next({name: 'welcome-login'});
    } else {
        next();
    }
})


export default router;